﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace InternetSpiderLib.Tools
{
    /// <summary>
    /// xml配置助手
    /// </summary>
    public class XmlConfig : DataBox
    {
        /// <summary>
        /// 根据文件初始化相关配置
        /// </summary>
        public void InitByFile(string file)
        {
            if (!File.Exists(file))
                return;

            XmlDocument document = new XmlDocument();
            document.Load(file);

            var items = document.SelectNodes("Config/Item");
            if (items != null)
            {
                foreach (XmlNode item in items)
                {
                    var key = item["Key"]?.InnerText;
                    var value = item["Value"]?.InnerText;
                    var type = item["Type"]?.InnerText;

                    if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(value) || string.IsNullOrEmpty(type))
                        continue;

                    var format_key = GetFormatKey(Type.GetType(type), key);
                    var obj = Convert.ChangeType(value, Type.GetType(type));

                    Name2Instance[format_key] = obj;
                }
            }
        }
    }
}
